package com.qzw.utils.mysql.generator;

import com.qzw.common.data.BaseMysqlDao;
import lombok.Data;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
 * @author ：quziwei
 * @date ：Created in 2020/6/7 6:05 上午
 * @description：Dao生成器类
 */
@Data
public class DaoGenerator extends AbstractGenerator {

    private String classTemplate = "@Repository%npublic interface %s extends BaseMysqlDao<%s, %s> {%n%n}";

    public DaoGenerator() {
        setSuffix("Dao");
    }

    @Override
    public void generator() {
        List<Class> entities = getEntities();
        String packageName = getPackageName();
        if (StringUtils.isEmpty(packageName)) {
            return;
        }
        String path = GeneratorUtils.getPath(packageName, getBasePath());
        for (Class clazz : entities) {
            // 构建类名
            String className = buildClassName(clazz);
            String newClazz = buildClassType(clazz);
            File file = new File(path + "/" + className + ".java");
            if (file.exists()) {
                System.out.println(newClazz + "已存在");
                continue;
            }
            StringBuilder stringBuilder = new StringBuilder();

            // 设置包名
            appendPackage(stringBuilder);

            // 组织引用类
            List<String> imports = new ArrayList<>();
            imports.add(BaseMysqlDao.class.getTypeName());
            imports.add(Repository.class.getTypeName());
            imports.add(clazz.getTypeName());
            String[] pk = GeneratorUtils.getGenericSuper(clazz);
            imports.add(pk[1]);
            appendImport(stringBuilder, imports);

            //设置类
            stringBuilder.append(String.format(classTemplate, className, clazz.getSimpleName(), pk[0]));

            // 执行生成
            GeneratorUtils.write(file, stringBuilder);

            System.out.println(newClazz);

        }
    }
}
